﻿using Microsoft.AspNetCore.Authorization;
using QBZ.Evaluation.Models;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
namespace QBZ.Evaluation.Domains.Permissions
{

    public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionAuthorizationRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement)
        {
            if (context.User != null)
            {
                if (context.User.IsInRole( UserLevel.SuperAdmin.ToString()))
                {
                    context.Succeed(requirement);
                }
                else
                {
                    //var userIdClaim = context.User.FindFirst(_ => _.Type == ClaimTypes.NameIdentifier);
                    var userLevelClaim = context.User.FindFirst(_ => _.Type == "UserLevel");
                    if (userLevelClaim != null)
                    {
                        if((UserLevel)Enum.Parse(typeof(UserLevel),userLevelClaim.Value) >=requirement.Level)
                        {
                            context.Succeed(requirement);
                        }
                    }
                }
            }
            return Task.CompletedTask;
        }
    }
}
